import axios from '../http'

const api = '/api/v2/goods/';

const error = (e) => {
  return () => console.error(e);
};

const toSpecifications = (specifications) => {
  let spec = [];
  for (let name in specifications) {
    if (name !== '颜色') {
      // {name: '制式', values:[{name:"全网通",noSelect: false}], selectedValue: '全网通'},
      spec.push({
        name: name,
        values: specifications[name].map(o => ({
          name: o,
          noSelect: false
        })),
        selectedValue: ''
      })
    }
  }
  return spec;
};

export function getGoods(id, cb, fcb = error('getGoods')) {
  axios.get(api + id,).then(d => {
    let goods = d.data;
    goods.thumb = goods.picture.substr(0, goods.picture.length - 1).split(",");
    goods.specifications = toSpecifications(goods.specifications);
    goods.picture = goods.picture.split(',')[0];
    cb(goods)
  }).catch(d => fcb(d))
}

export function listSku(id, cb, fcb = error('listSku')) {
  axios.get(api + id+"/sku",).then(d => {
    let data = d.data;
    for(let item of data){
      item.currentNum = 0;
      item.stepperLimit = item.stock;
      item.quota = 0;
      item.color= item.attributes['颜色'];
    }
    cb(data)
  }).catch(d => fcb(d))
}